import ZIM from "@/js_sdk/zego-ZIMUniplugin-JS/lib/ZIM.js";

import { dateTime } from "@/utils/utils.js";
import submit from "@/components/submit/submit.vue";
import {
  stopAnswer,
  getPrompt,
  revokeMSg,
  getQuickReply,
  setEntering,
  getQuizDetail_chat,
  check_read,
  sendCheck,
  backupMessage,
  end_now_chat,
  isWorkDay,
  evaluate,
  satisfied,
  reportMsg,
} from "@/static/js/quiz.js";
import { answerList } from "@/static/js/message.js";
import { getUserInfo } from "@/static/js/user";
export default {
  components: {
    submit,
  },
  data() {
    return {
      mainData: {}, //数据大对象
      entering: false, // 对方是否正在输入
      title: "问一问", //实际显示在界面上的标题
      msg: "", //输入框的内容
      showTimeTooltip: false, //结束前提醒
      evaluateShow: false, //评价弹框
      currentItem: 0,
      count: 5, //评价星星数
      starValue: 0, //星星值
      inputTxt: "", //输入框中的评价
      label: "", //评价标签名
      itemTxtList1: [
        {
          name: "没解决问题",
          checked: false,
        },
        {
          name: "不专业",
          checked: false,
        },
        {
          name: "态度很差",
          checked: false,
        },
        {
          name: "回复太慢",
          checked: false,
        },
        {
          name: "听不懂回答",
          checked: false,
        },
        {
          name: "回答敷衍",
          checked: false,
        },
      ],
      itemTxtList2: [
        {
          name: "回复太慢",
          checked: false,
        },
        {
          name: "回答敷衍",
          checked: false,
        },
        {
          name: "听不懂回答",
          checked: false,
        },
        {
          name: "不够专业",
          checked: false,
        },
        {
          name: "听不懂回答",
          checked: false,
        },
        {
          name: "没解决问题",
          checked: false,
        },
      ],
      itemTxtList3: [
        {
          name: "态度一般",
          checked: false,
        },
        {
          name: "回答不够认真",
          checked: false,
        },
        {
          name: "不够专业",
          checked: false,
        },
        {
          name: "回答不够清楚",
          checked: false,
        },
        {
          name: "回答较慢",
          checked: false,
        },
        {
          name: "解决部分问题",
          checked: false,
        },
      ],
      itemTxtList4: [
        {
          name: "态度热情",
          checked: false,
        },
        {
          name: "回复很及时",
          checked: false,
        },
        {
          name: "专业度高",
          checked: false,
        },
        {
          name: "解决了问题",
          checked: false,
        },
        {
          name: "回答很认真",
          checked: false,
        },
        {
          name: "回答很清楚",
          checked: false,
        },
      ],
      itemTxtList5: [
        {
          name: "态度非常好",
          checked: false,
        },
        {
          name: "回答迅速",
          checked: false,
        },
        {
          name: "回答很专业",
          checked: false,
        },
        {
          name: "解决了问题",
          checked: false,
        },
        {
          name: "回答很认真",
          checked: false,
        },
        {
          name: "回答很清楚",
          checked: false,
        },
      ],

      userInfo: {}, //用户信息
      user_id: "", //用户id
      imgUrl: [], //图片地址
      scrollToView: "",

      inputHeight: "80",

      quiz_id: "", //问题id
      quizData: {}, //问题详情

      message: "", //发送的消息
      curMessageList: [], //当前展示的聊天消息

      isJudge: false, //是否已评价
      hasInitZIM: false, //是否已经初始化zim

      endChat: false, //确定结束对话

      deadline: 0, //结束时间
      now: 0, //当前时间
      endTime: 0, //结束时间

      isWorkdays: true, //当前是否为工作日
      bottomVal: "",
      scrollViewHeight: "100vh",
      sendHeight: 0,

      wenda_reminder: "", //温馨提示
      oftenList: [],
      showOftenMsg: false,
      unSatisfied: false, //不满意弹窗
      reasonMsg: "", //不满意理由
      is_satisfied: 0, //是否满意
      btnActive: 0,
      msgId: "", //消息id

      isInputFocus: false, //键盘是否弹起

      promptList: "", //提示语

      isStop: 0, //0=正常状态  1=暂停状态
      answerType: null,

      getAvatar: (senderUserID) => {
        if (senderUserID == this.quizData.ans_uid) {
          return this.mainData.ans_uid.avatar;
        } else {
          return this.mainData.uid.avatar;
        }
      },
      getNickname: (senderUserID) => {
        if (senderUserID == this.quizData.ans_uid) {
          return this.mainData.ans_uid.nickname;
        } else {
          return this.mainData.uid.nickname;
        }
      },

      reportPopup: false, //举报弹窗
      reportType: [
        {
          type: "广告内容",
          id: 1,
        },
        {
          type: "不友善内容",
          id: 2,
        },
        {
          type: "造谣,伪科学",
          id: 3,
        },
        {
          type: "违法违规",
          id: 4,
        },
        {
          type: "青少年不宜",
          id: 5,
        },
        {
          type: "其他",
          id: 6,
        },
      ], //举报类型

      showPointsTips: false, //任务完成提示
      pointsTipsTitle: "", //任务完成提示标题
      points: "", //任务完成提示积分
    };
  },
  onLoad(e) {
    this.getUserInfo();
    this.quiz_id = e.id;
    this.answerType = e.type;
    this.isWorkDay();
    setTimeout(() => {
      const query = uni.createSelectorQuery().in(this);
      query
        .select(".submit-send")
        .boundingClientRect((data) => {
          this.sendHeight = data.height;
        })
        .exec();
    }, 500);

    this.goBottom();
    this.getQuickReply();
    this.getPrompt();

    if (e.showPointsTips) {
      setTimeout(() => {
        this.showPointsTips = e.showPointsTips;
        this.pointsTipsTitle = e.pointsTipsTitle;
        this.points = Number(e.points);
      }, 1000);

      setTimeout(() => {
        this.showPointsTips = false;
      }, 3000);
    }
  },
  onShow() {
    this.getUserInfo();
    setTimeout(() => {
      this.getQuizDetail(true);
    }, 500);
    //zim注册监听
    this.initZim();
  },
  onHide() {
    this.getMessage();
  },
  mounted: function () {
  },

  destroyed() {
    ZIM.getInstance().off("receivePeerMessage");
    let serverNum = this.$store.state.serverNum ? this.$store.state.serverNum : 0;
    let wdNum = this.$store.state.wdNum ? this.$store.state.wdNum : 0;
    if (serverNum + wdNum == 0) {
      uni.removeTabBarBadge({
        index: 3,
      });
    }
  },
  computed: {
    showText() {
      return this.quizData.status == 1 && this.quizData.uid == this.userInfo.id;
    },
    showText1() {
      return (
        this.quizData.status == 1 &&
        this.quizData.uid == this.userInfo.id &&
        this.isWorkdays
      );
    },
    showText2() {
      return (
        this.quizData.status == 1 &&
        this.quizData.uid == this.userInfo.id &&
        !this.isWorkdays
      );
    },
    showText3() {
      return (
        this.showTimeTooltip &&
        this.quizData.uid == this.userInfo.id &&
        this.quizData.status != 3
      );
    },
    showText4() {
      return (
        this.quizData.status == 3 &&
        (this.quizData.uid == this.userInfo.id ||
          this.quizData.ans_uid == this.userInfo.id)
      );
    },

    webSocketMessage() {
      return this.$store.state.webSocketMessage;
    },
  },
  watch: {
    //设置标题
    curMessageList(newMessage, oldMessage) {
      this.title = "问一问";
      let userInfo = uni.getStorageSync("userInfo");
      for (let i = 0; i < this.curMessageList.length; i++) {
        let msgUserId = this.curMessageList[i].extendedData.id;
        if (msgUserId != null && msgUserId != "" && msgUserId != userInfo.id) {
          this.title =
            "与" + this.curMessageList[i].extendedData.nickname + "的会话";
          break;
        }
      }
      uni.setNavigationBarTitle({
        title: this.entering ? "对方正在输入" : this.title,
      });
    },
    entering(newV, oldV) {
      uni.setNavigationBarTitle({
        title: this.entering ? "对方正在输入" : this.title,
      });
    },

    webSocketMessage(newV, oldV) {
      if (newV.content == 1) return;
      let messageContent = newV.content;
      let data = JSON.parse(messageContent);

      if (data && data.type) {
        if (data.type == 2) {
          this.entering = data.entering == 1;
        } else if (data.type == "askClose" || data.type == "revokeMsg") {
          this.getQuizDetail(true);
        }
      }
    },
  },

  methods: {
    //暂停时间
    async stopAnswer(status) {
      this.isStop = status;
      let res = await stopAnswer({
        quiz_id: this.quiz_id,
        status,
      });
      this.isStop = status;
      if (res.code == 1) {
        console.log("已暂停");
      }
    },
    //获取提示语
    async getPrompt() {
      let res = await getPrompt();
      if (res.code == 1) {
        let arr = [];
        res.data.forEach((val) => {
          let str = val.content;
          arr.push(str);
        });
        this.promptList = arr.join("");
      }
    },
    longpress() {
      this.getQuizDetail(true);
    },

    //计算操作菜单
    claActionMenu(item) {
      let now = new Date().getTime();
      let timeDifference = now - item.timestamp;
      if (timeDifference < 60000) {
        return ["引用", "撤回"];
      } else {
        return ["引用"];
      }
    },

    //对方点击提示
    clickTip1(index, item) {
      this.msgId = item.extendedData.msgId;
      if (index == 1) {
        // 组装引用的消息
        var quoteObj = {
          nickname: item.extendedData.nickname,
          message: item.message,
        };
        this.$refs.submit.quoteMessage(quoteObj);
      } else if (index == 2) {
        this.reportPopup = true;
      }
    },

    //点击提示
    clickTip(index, item) {
      this.msgId = item.extendedData.msgId;
      if (index == 1) {
        // 组装引用的消息
        var quoteObj = {
          nickname: item.extendedData.nickname,
          message: item.message,
        };
        this.$refs.submit.quoteMessage(quoteObj);
      } else if (index == 2) {
        if (this.userInfo.id == item.extendedData.id) {
          this.revokeMSg();
        }
      }
    },

    //撤回
    async revokeMSg() {
      var params = {
        message_id: this.msgId,
        //传对方的id
        user_id:
          this.userInfo.id == this.quizData.uid
            ? this.quizData.ans_uid
            : this.quizData.uid,
      };
      let res = await revokeMSg(params);
      if (res.code == 1) {
        this.goeasyRevokeMsg();
        this.getQuizDetail(true);
      }
    },

    // 通过goeasy通知对方消息已撤回
    goeasyRevokeMsg() {
      let message = {
        type: "revokeMsg",
        message_id: this.msgId,
      };
      let messageStr = JSON.stringify(message);
      let toUserId = "";
      if (this.userInfo.id == this.quizData.uid) {
        toUserId = this.quizData.ans_uid;
      } else {
        toUserId = this.quizData.uid;
      }
      this.$goeasy.pubsub.publish({
        channel: toUserId,
        message: messageStr,
        onSuccess: function () {
          console.log("消息发布成功。");
        },
        onFailed: function (error) {
          console.log("消息发送失败" + error.content);
        },
      });
    },

    //获取常用语
    async getQuickReply() {
      let res = await getQuickReply();
      if (res.code == 1) {
        this.oftenList = res.data;
      } else {
        this.$tools.msg(res.msg);
      }
    },

    // 通过goeasy通知对方问题已结束
    chatClose() {
      let message = {
        type: "askClose",
        quiz_id: this.quizData.id,
      };
      let messageStr = JSON.stringify(message);
      this.$goeasy.pubsub.publish({
        channel: this.quizData.ans_uid,
        message: messageStr,
        onSuccess: function () {
          console.log("消息发布成功。");
        },
        onFailed: function (error) {
          console.log("消息发送失败" + error.content);
        },
      });
    },

    //获取个人用户信息
    async getUserInfo() {
      getUserInfo().then((res) => {
        this.userInfo = res.data;
      });
    },

    //通过GoEasy告知对方我的输入状态
    async setEntering(is) {
      if (this.quizData.status != 2) return;

      let toUserId = "";
      if (this.userInfo.id == this.quizData.uid) {
        toUserId = this.quizData.ans_uid;
      } else {
        toUserId = this.quizData.uid;
      }
      var params = {
        uid: toUserId,
        quiz_id: this.quiz_id,
        entering: is ? 1 : 0,
      };
      let res = await setEntering(params);
    },

    hideKeyboard() {
      this.$refs.submit.hideMore();
    },

    //通过键盘高度变化跟踪消息
    changeBottomVal(val) {
      //对方是否在输入
      this.setEntering(val > 0);
      this.bottomVal = val > 0 ? val - 80 : val;
      this.scrollViewHeight = `calc(100vh - ${this.sendHeight}rpx)`;
      this.scrollToView = "";
      setTimeout(() => {
        this.scrollToView =
          "msgItem" +
          this.curMessageList[this.curMessageList.length - 1].timestamp;
      }, 200);
    },

    //通过更多高度变化跟踪消息
    moreBtn() {
      this.scrollToView = "";
      setTimeout(() => {
        this.scrollToView =
          "msgItem" +
          this.curMessageList[this.curMessageList.length - 1].timestamp;
      }, 200);
    },

    // 获取问题详情
    async getQuizDetail(needLoadHistory) {
      let userInfo = uni.getStorageSync("userInfo");
      var params = {
        quiz_id: this.quiz_id,
      };
      const res = await getQuizDetail_chat(params);
      if (res.code == 1) {
        //问题详情
        this.mainData = res.data;
        this.quizData = res.data.quiz;
        this.wenda_reminder = res.data.wenda_reminder;
        this.endTime = res.data.chatroom.endtime * 1000;

        let now = new Date().getTime();
        this.deadline = this.endTime - now;

        if (
          this.quizData.uid != null &&
          this.quizData.uid != "" &&
          this.quizData.ans_uid != null &&
          this.quizData.ans_uid != ""
        ) {
          let index = (this.quizData.uid + "_" + this.quizData.ans_uid).indexOf(
            userInfo.id
          );
          if (index == -1) {
            //关闭当前界面退回到上一页面
            uni.navigateBack({
              delta: 1,
            });
            return;
          }
        }

        this.showOftenMsg = this.quizData.uid === userInfo.id;

        //历史消息
        if (needLoadHistory) {
          this.curMessageList = [];
          var msg0 = {
            direction: 0,
            timestamp: this.quizData.add_time * 1000,
            extendedData: {
              avatar: this.quizData.avatar,
              nickname: this.quizData.nickname,
              id: this.quizData.uid,
              type: 1,
              msgRevoke: 0,
            },
            sentStatus: 1,
            senderUserID: this.quizData.uid + "",
            message: this.quizData.title,
            type: 1,
            conversationType: 0,
          };
          this.curMessageList.push(msg0);

          //2、图片展示
          if (
            this.quizData.info_images != null &&
            this.quizData.info_images != ""
          ) {
            if (this.quizData.info_images.indexOf(",") > -1) {
              var images = this.quizData.info_images.split(",");
              for (let image of images) {
                var imageMessage = {
                  direction: 0,
                  timestamp: this.quizData.add_time * 1000,
                  extendedData: {
                    avatar: this.quizData.avatar,
                    nickname: this.quizData.nickname,
                    id: this.quizData.uid,
                    type: 11,
                    msgRevoke: 0,
                  },
                  sentStatus: 1,
                  senderUserID: this.quizData.uid + "",
                  message: image,
                  type: 1,
                  conversationType: 0,
                };
                this.curMessageList.push(imageMessage);
              }
            } else {
              var imageMessage = {
                direction: 0,
                timestamp: this.quizData.add_time * 1000,
                extendedData: {
                  avatar: this.quizData.avatar,
                  nickname: this.quizData.nickname,
                  id: this.quizData.uid,
                  type: 11,
                  msgRevoke: 0,
                },
                sentStatus: 1,
                senderUserID: this.quizData.uid + "",
                message: this.quizData.info_images,
                type: 1,
                conversationType: 0,
              };
              this.curMessageList.push(imageMessage);
            }
          }
          this.getHistoryMessage(res.data.chatroomtext);
        }

        this.goBottom();

        //注册监听
        this.initZim();
        if (this.timeInterval) clearInterval(this.timeInterval);
        this.timeInterval = setInterval(() => {
          this.changMessageList();
        }, 2000);
      }
    },

    // 历史消息
    getHistoryMessage(chatroomtext) {
      try {
        for (let item of chatroomtext) {
          let message = JSON.parse(item.message);
          message.extendedData.msgId = item.id;
          message.extendedData.msgRevoke = item.is_revoke;
          this.curMessageList.push(message);
        }
      } catch (error) { }
      for (let i = 0; i < this.curMessageList.length; i++) {
        if (this.curMessageList[i].extendedData.id != this.userInfo.id) {
          this.title =
            "与" + this.curMessageList[i].extendedData.nickname + "的会话";
          break;
        }
      }
      uni.setNavigationBarTitle({
        title: this.entering ? "正在输入中" : this.title,
      });
    },

    // 初始化zim
    initZim() {
      let that = this;

      if (that.hasInitZIM) {
        return;
      }
      that.hasInitZIM = true;
      var zim = ZIM.getInstance();
      // 监听“运行时错误信息”
      zim.on("error", function (zim, errorInfo) { });

      // 注册监听“网络连接状态变更”
      zim.on(
        "connectionStateChanged",
        function (zim, { state, event, extendedData }) {
          // 当长时间网络连接断开导致SDK内部登出时，需要重新登录
          if (state == 0 && event == 3) {
            //zim登录
            that.$zegoUtils.zimLogin();
          }
        }
      );
      // 注册监听“令牌即将过期”的回调
      zim.on("tokenWillExpire", function (zim, { second }) {
        ZIM.getInstance().logout();
        setTimeout(() => {
          that.$zegoUtils.zimLogin();
        }, 200);
      });

      // 监听对方的已读状态
      zim.on("messageReceiptChanged", function (zim, zimRes) {
        for (let messageItem of that.curMessageList) {
          if (messageItem.senderUserID == that.userInfo.id) {
            messageItem.receiptStatus = 2;
          }
        }
        check_read({
          quiz_id: that.quizData.id,
          user_id: that.userInfo.id,
        });
      });

      // 注册监听“收到单聊消息”的回调
      zim.on("receivePeerMessage", function (zim, zimRes) {
        let { messageList, fromConversationID } = zimRes;

        //判断当前界面是否显示可见，可见的情况下才调用已读动作
        zim
          .sendMessageReceiptsRead(messageList, fromConversationID, 0)
          .then(function ({
            conversationID,
            conversationType,
            errorMessageIDs,
          }) {
            that.getMessage();
          })
          .catch(function (err) {
            // 操作失败
          });

        check_read({
          quiz_id: that.quizData.id,
          user_id: that.userInfo.id,
        });

        setTimeout(() => {
          that.getQuizDetail(true);
        }, 1500);
      });
    },

    /**
     * 点击发送
     * @param {对象} quoteMsg 被引用的消息对象,有可能为空
     * @param {数字} messageType 消息类型 1=文字  11=图片
     * @param {String} msg 消息内容
     */
    async clickSend(msg, messageType, quoteMsg) {
      this.msg = msg;
      //发送前检查
      var params = {
        quiz_id: this.quizData.id,
      };
      let res = await sendCheck(params);
      if (res.code == 1) {
        this.realZimSend(msg, messageType, quoteMsg);
      } else {
        this.$tools.msg(res.msg);
      }
      setTimeout(() => {
        this.scrollToView =
          "msgItem" +
          this.curMessageList[this.curMessageList.length - 1].timestamp;
      }, 500);
    },

    /**
     * ZIM真实发送
     * @param {对象} quoteMsg 被引用的消息对象,有可能为空
     * @param {String} msg 如果messageType=1则为文字，如果messageType=2则为图片地址
     * @param {数字} messageType 消息类型 1=文字  11=图片
     */
    realZimSend(msg, messageType, quoteMsg) {
      var userInfo = uni.getStorageSync("userInfo");

      let extendedInfo = {
        avatar: userInfo.avatar,
        nickname: userInfo.nickname,
        id: userInfo.id,
        type: messageType,
        quiz_id: this.quizData.id,
        quoteMsg: quoteMsg, //引用的消息
      };

      var messageTextObj = {
        type: 1,
        message: msg,
        extendedData: JSON.stringify(extendedInfo),
      };

      //确定消息发送给谁
      var toConversationID;
      if (userInfo.id == this.quizData.uid) {
        //我是提问人-->发送给回答人
        if (
          this.quizData.ans_uid == null ||
          this.quizData.ans_uid == "" ||
          this.quizData.ans_uid == undefined
        ) {
          this.$tools.msg("暂时无人回答");
          return;
        }
        toConversationID = this.quizData.ans_uid + "";
      } else {
        //我是回答人-->发送给提问人
        toConversationID = this.quizData.uid + "";
      }

      // 会话类型，取值为 单聊：0，房间：1，群组：2
      var conversationType = 0;

      //设置消息优先级
      var config = {
        priority: 1, // 设置消息优先级，取值为 低：1（默认），中：2，高：3
        hasReceipt: true, // 设置消息带回执
      };

      var notification = {
        onMessageAttached: function (msg) {
          console.log('onMessageAttached·····', msg)
        },
      };
      let that = this;
      ZIM.getInstance()
        .sendMessage(
          messageTextObj,
          toConversationID,
          conversationType,
          config,
          notification
        )
        .then(function (zimMessage) {
          if (that.quizData.status == 3) {
            //服务结束
            if (that.quizData.uid != that.userInfo.id && that.answerType == 1) {
              that.backupMessage(zimMessage, msg, 1); //传服务器
            } else {
              that.$tools.msg("服务已结束");
            }
          } else {
            //服务没结束
            that.backupMessage(zimMessage, msg, 0); //传服务器
          }
        })
        .catch(function (err) {
          //调用登录方法->登录成功->重新发送
          that.$zegoUtils
            .zimLogin()
            .then(() => {
              that.realZimSend(msg, messageType);
            })
            .catch(function (err) {
              that.realZimSend(msg, messageType);
            });
        });
    },

    /**
     * 将发送的消息上传给服务器
     * oriMsg = 原始消息内容
     * param is_supplement 1=补充消息 0=正常消息
     */
    async backupMessage(zimMessage, oriMsg, is_supplement) {
      if (this.quizData.uid != this.userInfo.id) {
        //已暂停的状态
        this.stopAnswer(0); //0表示解除暂停
      }
      var userInfo = uni.getStorageSync("userInfo");
      var sendRes = {
        ...zimMessage.message,
      };
      if (sendRes.message) {
        sendRes.message = sendRes.message.replace(/%/g, "%25");
        sendRes.message = sendRes.message.replace(/\+/g, "%2B");
        sendRes.message = sendRes.message.replace(/</g, "%3C");
        sendRes.message = sendRes.message.replace(/>/g, "%3E");
        sendRes.message = sendRes.message.replace(/\&/g, "%26");
        sendRes.message = sendRes.message.replace(/&/g, "&amp;");
      } else return;

      sendRes.extendedData = JSON.parse(sendRes.extendedData);

      var data = {
        type: 2,
        quiz_id: this.quizData.id,
        message: JSON.stringify(sendRes),
        senderUserId: userInfo.id,
        role: userInfo.id == this.quizData.uid ? 1 : 2,
        is_supplement,
      };

      let res = await backupMessage(data);
      if (res.code == 1) {
        if (sendRes.message)
          sendRes.message = decodeURIComponent(sendRes.message);
        //渲染到页面
        this.curMessageList.push(sendRes);
        this.goBottom();

        this.getQuizDetail(true);
      } else {
        this.$tools.msg(res.msg);
      }
    },

    // 时间循环检查提问距离结束的时间
    changMessageList() {
      if (this.quizData.status == 3) {
        clearInterval(this.timeInterval);
        return;
      }
      if (this.curMessageList.length == 0) return;
      let message = this.curMessageList[this.curMessageList.length - 1];

      // 如果最后一条消息是提问者的，不判断倒计时
      if (message.senderUserID != this.quizData.ans_uid) {
        this.showTimeTooltip = false;
        return;
      }

      // 获取时间戳
      let time = new Date().getTime();
      let timeDifference = time - message.timestamp;
      if (timeDifference > 180000) {
        this.checkAskIsClose();
      } else if (timeDifference > 120000) {
        this.showTimeTooltip = true;
      } else {
        this.showTimeTooltip = false;
      }
    },
    // 检查问题是否结束
    async checkAskIsClose() {
      const res = await getQuizDetail_chat({
        quiz_id: this.quiz_id,
        status: 0,
      });
      if (res.code == 1) {
        if (res.data.quiz.status == 3) {
          this.quizData = res.data.quiz;
          clearInterval(this.timeInterval);
          this.chatClose();
        } else {
          console.log("问题未结束");
        }
      }
    },
    // 结束问题
    async closeAsk() {
      const res = await end_now_chat({
        quiz_id: this.quizData.id,
      });
      if (res.code == 1) {
        this.getQuizDetail(false);
        this.chatClose();
      }
    },
    //获取当前是否为工作日
    async isWorkDay() {
      var res = await isWorkDay();
      if (res.code == 0) {
        this.isWorkdays = false;
      } else {
        this.isWorkdays = true;
      }
    },
    // 根据星星数量显示字符
    showTitle(starValue) {
      //总评价
      var text = "";
      switch (starValue) {
        case 1:
          text = "不满意，各方面都很差";
          break;
        case 2:
          text = "不满意，待提高";
          break;
        case 3:
          text = "一般般，仍可改善";
          break;
        case 4:
          text = "比较满意，仍可改善";
          break;
        case 5:
          text = "特别棒，无可挑剔";
          break;
      }
      return text;
    },

    //选择评论项
    chooseItem(item, index) {
      this.label = item.name;
      this.currentItem = index;
      if (this.currentItem == index) {
        item.checked = !item.checked;
      }
    },

    //提交评价
    async evaluate() {
      var params = {
        quiz_id: this.quizData.id,
        star: this.starValue,
        label: this.label ? this.label : "",
        evaluate: this.inputTxt,
      };
      var res = await evaluate(params);
      if (res.code == 1) {
        this.$tools.msg("评价成功");
        this.evaluateShow = false;
        this.getQuizDetail(true);
      }
    },

    // 满意结果录入  isSatisfied 是否满意 false=不满意 true=满意
    satisfied(isSatisfied) {
      if (isSatisfied) {
        this.btnActive = 0;
        this.starValue = 5;
        this.is_satisfied = 1;
        this.evaluateShow = true;
        this.unSatisfied = false;
        this.submitReason();
      } else {
        this.btnActive = 1;
        this.starValue = 3;
        this.is_satisfied = 2;
        this.unSatisfied = true;
      }
    },

    //提交不满意原因
    async submitReason() {
      if (this.reasonMsg == "" && this.is_satisfied == 2) {
        this.$tools.msg("请输入不满意原因");
        return;
      }
      var params = {
        quiz_id: this.quizData.id,
        is_satisfied: this.is_satisfied,
        reason: this.reasonMsg,
      };
      var res = await satisfied(params);
      if (res.code == 1) {
        this.evaluateShow = true;
        this.isJudge = true;
        this.getQuizDetail(true);
      } else {
        this.$tools.msg(res.msg);
      }
    },
    // 格式化时间
    changeTime(date) {
      return dateTime(date);
    },
    // 进行图片的预览
    previewImg(e) {
      uni.previewImage({
        urls: [e],
      });
    },

    //输入框高度
    heights(e) {
      this.inputHeight = 2 * e;
      this.goBottom();
    },

    // 滚动到底部
    goBottom() {
      let that = this;
      setTimeout(() => {
        that.scrollToView =
          "msgItem" +
          that.curMessageList[that.curMessageList.length - 1].timestamp;
      }, 800);
    },

    //接受输入内容
    inputs(e) {
      this.imgUrl = e;
    },

    goBack() {
      uni.navigateBack({
        delta: 1,
      });
    },

    // 举报弹窗关闭
    closeReport() {
      this.reportPopup = false;
    },

    //举报
    async onClickReport(e) {
      var res = await reportMsg({
        out_id: this.msgId,
        content: e.type,
      });
      if (res.code == 1) {
        this.reportPopup = false;
        this.$tools.msg("举报成功");
      }
    },

    // 获取问答
    async getMessage() {
      // 回答提问
      let res = await answerList({
        type: 5,
        page: 1,
        pagesize: 999,
      });
      if ((res.code = 1)) {
        console.log("清空问答未读数");
      }
    },
  },
};